package com.feituan.core.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feituan.core.persistence.mapper.OrderMapper;
import com.feituan.core.pojo.entity.EquipmentShop;
import com.feituan.core.pojo.entity.Order;
import com.feituan.core.pojo.entity.Product;
import com.feituan.core.pojo.request.PrinterRequest;
import com.feituan.core.service.IEquipmentShopService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Api(tags = "打印模板")
public class PrinterTemplate {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IEquipmentShopService equipmentShopService;
    public String generateAndPrintReceipt(Order order, List<Product> productList, String templateString) {

        // FreeMarker 配置
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);


        // 直接使用模板字符串创建 Template 对象
        Template template;
        try {
            template = new Template("receiptTemplate", new StringReader(templateString), cfg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 创建数据模型
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("orderSn", order.getOrderSn());
        dataModel.put("orderTime", order.getCreateTime());
        dataModel.put("roomName", order.getRoomName());
        dataModel.put("products", productList);
        dataModel.put("totalPrice", order.getOrderPrice());
        dataModel.put("phone", order.getPhone());

        // 生成收据
        StringWriter writer = new StringWriter();
        try {
            template.process(dataModel, writer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return writer.toString();
    }

    /**
     * 根据订单号和类型
     * @param orderSn orderSn
     * @param type type
     */
    public List<PrinterRequest> templateEquipment(String orderSn, String type) {
        Order order = orderMapper.selectByOrderSn(orderSn);
        List<Product> productList;
        List<PrinterRequest> printTemplateList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            productList = objectMapper.readValue(order.getProducts(), new TypeReference<List<Product>>() {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<EquipmentShop> equipmentShop = equipmentShopService.selectByTypeAndShopId(type, order.getMerchantId());
        for (EquipmentShop shop : equipmentShop) {
            PrinterRequest templateEquipment = new PrinterRequest();
            templateEquipment.setTemplate(generateAndPrintReceipt(order, productList, shop.getTemplate()));
            templateEquipment.setEquipmentCode(shop.getEquipmentCode());
            printTemplateList.add(templateEquipment);
        }
        return printTemplateList;
    }

    /**
     * 根据订单号
     * @param orderSn orderSn
     */
    public List<PrinterRequest> templateEquipment(String orderSn) {
        Order order = orderMapper.selectByOrderSn(orderSn);
        List<Product> productList;
        List<PrinterRequest> printTemplateList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            productList = objectMapper.readValue(order.getProducts(), new TypeReference<List<Product>>() {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<EquipmentShop> equipmentShop = equipmentShopService.selectByShopId(order.getMerchantId());
        for (EquipmentShop shop : equipmentShop) {
            PrinterRequest templateEquipment = new PrinterRequest();
            templateEquipment.setTemplate(generateAndPrintReceipt(order, productList, shop.getTemplate()));
            templateEquipment.setEquipmentCode(shop.getEquipmentCode());
            printTemplateList.add(templateEquipment);
        }
        return printTemplateList;
    }
}
